import React, { Component } from 'react'
import './editModal.scss'
import {  withRouter } from 'react-router-dom'
import district from "../city.js"
import { DatePicker , Cascader, message } from 'antd';
import { getApiConfig , getApiDictInfo  , getApiSaveCustomer } from "../../axios/api"
import moment from 'moment';
import "moment/locale/zh-cn";
import { get } from '../../axios/localstorage';
moment.locale('zh-cn')


class editModal extends Component {

    state = {
        show:false,
        configList:[],
        data:{},
        dicData:{},
        sex:'',
        showSex:false,
        sexList:['男','女'],

        module:'',
        isDisabled:true

     
    }

    componentWillMount(){
        window.scroll(0,0)
        this.setState({
            module:this.props.module,
            cityList:district
        })

        setTimeout(()=>{
            this.getConfig();

            this.getDicData();
        },100)
    }

//     体检  0无  1通过 2不通过
// 政审 0无  1通过 2不通过
// 定兵  0未定  1通过 2不通过
// 发放服装  0未发放  1已发放 2发放
// 退兵 0未定兵 1已退兵 

    componentWillReceiveProps(nextProps) { // 父组件重传props时就会调用这个方法
        console.log(nextProps);
        let data = nextProps.data;
        let disabled = nextProps.disabled;

        this.setState({
            isDisabled:disabled
        })

        if(data.gender === 1){
            data.gender = '男'
        }else{
            data.gender = '女' 
        }
        if(data.fz_state === 1){
            data.fz_state = '已发放'
        }else{
            data.fz_state = '未发放' 
        }
        if(data.tb_result === 1){
            data.tb_result = '已退兵'
        }else{
            data.tb_result = '未退兵 ' 
        }

        if(data.tj_result === 0){
            data.tj_result = '无'
        }else if(data.tj_result === 1){
            data.tj_result = '通过'
        }else if(data.tj_result === 2){
            data.tj_result = '不通过'
        }

        if(data.zs_result === 0){
            data.zs_result = '无'
        }else if(data.zs_result === 1){
            data.zs_result = '通过'
        }else if(data.zs_result === 2){
            data.zs_result = '不通过'
        }

        if(data.db_result === 0){
            data.db_result = '未定'
        }else if(data.db_result === 1){
            data.db_result = '通过'
        }else if(data.db_result === 2){
            data.db_result = '不通过'
        }


        this.setState({
            data
        })
    }


    gotoAdd=()=>{

        // if(this.state.module === "rbqk"){
            
        // }

        this.addCustomer();

        

    }

    checkIDCard=(idcode)=>{
                 // 加权因子
                var weight_factor = [7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2];
                // 校验码
                var check_code = ['1', '0', 'X' , '9', '8', '7', '6', '5', '4', '3', '2'];
            
                var code = idcode + "";
                var last = idcode[17];//最后一位
            
                var seventeen = code.substring(0,17);
            
                // ISO 7064:1983.MOD 11-2
                // 判断最后一位校验码是否正确
                var arr = seventeen.split("");
                var len = arr.length;
                var num = 0;
                for(var i = 0; i < len; i++){
                    num = num + arr[i] * weight_factor[i];
                }
                
                // 获取余数
                var resisue = num%11;
                var last_no = check_code[resisue];
            
                // 格式的正则
                // 正则思路
                /*
                第一位不可能是0
                第二位到第六位可以是0-9
                第七位到第十位是年份，所以七八位为19或者20
                十一位和十二位是月份，这两位是01-12之间的数值
                十三位和十四位是日期，是从01-31之间的数值
                十五，十六，十七都是数字0-9
                十八位可能是数字0-9，也可能是X
                */
                var idcard_patter = /^[1-9][0-9]{5}([1][9][0-9]{2}|[2][0][0|1][0-9])([0][1-9]|[1][0|1|2])([0][1-9]|[1|2][0-9]|[3][0|1])[0-9]{3}([0-9]|[X])$/;
            
                // 判断格式是否正确
                var format = idcard_patter.test(idcode);
            
                // 返回验证结果，校验码和格式同时正确才算是合法的身份证号码
                return last === last_no && format ? true : false;
    }

    addCustomer=()=>{
        let param = this.state.data;
        // if(!param.name){
        //     message.info('请输入姓名！');
        //     return false;
        // }
        // if(!param.date_of_birth){
        //     message.info('请选择出生日期！');
        //     return false;
        // }
        // if(!param.native_place){
        //     message.info('请选择籍贯！');
        //     return false;
        // }
        // if(!param.education_code){
        //     message.info('请选择学历！');
        //     return false;
        // }
        // if(!param.gender){
        //     message.info('请选择性别！');
        //     return false;
        // }
        // if(!param.identity_num){
        //     message.info('请输入身份ID！');
        //     return false;
        // }

        // let isCard = this.checkIDCard(param.identity_num);
        // if(!isCard){
        //     message.info('请输入正确的身份ID！');
        //     return false;
        // }

        // if(!param.nation_code){
        //     message.info('请选择民族！');
        //     return false;
        // }
        // if(!param.group_code){
        //     message.info('请选择分组！');
        //     return false;
        // }
        
        param.module = this.state.module;
        param.user_id = param.id;
        param.token = get('token');

        getApiSaveCustomer(param)
        .then( req =>{
            console.log(req.data)
            if(req.data.code === 1){
                this.props.updateData();
            }else{
                message.info(req.data.msg);
            }
        }).catch( err =>{
            console.error(err);
        })
    }

    

    getDicData=()=>{
        getApiDictInfo()
        .then( req =>{
            console.log(req.data)
            if(req.data.code === 1){
                this.setState({
                    dicData:req.data.data
                })
            }
        }).catch( err =>{
            console.error(err);
        })
    }

    getConfig=()=>{
        let param = {
            module:this.state.module,
            token:get('token')
        }

        getApiConfig(param)
        .then( req =>{
            console.log(req.data)
            if(req.data.code === 1){
                this.setState({
                    configList:req.data.data
                })
            }
        }).catch( err =>{
            console.error(err);
        })
    }

    gotoChooseSex=(item)=>{
        let data = this.state.data;
        data.gender = item;
        this.setState({
            showSex:false,
            data
        })
    }

    gotoRemoveGender=(event)=>{
        event.stopPropagation();

        let data = this.state.data;

        data.gender = '';

        this.setState({
            data
        })
    }

    onChangeDate=(value,str,item)=>{
        

        let data = this.state.data;
        let key = item.key;
        data[key] = str;

        console.log(data)
        this.setState({
            data
        })
    }

    onChange=(value,selectedOptions,item) =>{
        console.log(value);
        console.log(selectedOptions);
    
        let options = selectedOptions;
    
        let str = options[0]['label'] + '/' +options[1]['label'] 
   
    
        console.log(str);

        let data = this.state.data;
        let key = item.key;
        data[key] = str;
    
        this.setState({
            data
        })
        
    }

    gotoChangeValue=(event,item)=>{


        let value = event.target.value;

        let data = this.state.data;
        let key = item.key;

        data[key]  = value;

        this.setState({
            data
        })

    }

    gotoRemove=(event,item)=>{
        event.stopPropagation();

        let data = this.state.data;
        let key = item.key;

        data[key]  = '';

        this.setState({
            data
        })
    }


    gotoShow=(index)=>{
        let configList = this.state.configList;
        configList[index].show = !configList[index].show;
        this.setState({
            configList
        })
    }

    gotoLeave=(index)=>{
        let configList = this.state.configList;
        configList[index].show = false;
        this.setState({
            configList
        })
    }

    gotoChoose=(elem,item,index)=>{
        let data = this.state.data;
        let key = item.key;
        data[key]  = JSON.stringify(elem);
        let configList = this.state.configList;
        for(var i =0;i<configList.length;i++){
            configList.show = false;
        }
        console.log(data);
        console.log(configList);
        this.setState({
            data,
            configList
        })

        // forceUpdate();
    }

    do=(item,data)=>{

        if(item.type === "select"){

            if(item.key === 'gender'){
                return false;
            }
            


            if (typeof data == 'string') {
                try {
                    var obj=JSON.parse(data);
                    if(typeof obj === 'object' && obj ){
                        let key = JSON.parse(data);
                        return key.name;
                    }else{
                        return data;
                    }
        
                } catch(e) {
                    console.log('error：'+data+'!!!'+e);
                    return data;
                }
            }
        
            // return key.name;
        }
    }




    render() {
        return (
            <div className="editModal" hidden={!this.props.show}>
                <div className="abox">
                        <h1>人员信息</h1>
                        <div className="aitems">
                        {
                            this.state.configList.map((item,index)=>{
                                return <div key={index}>
                                            <div className="item" hidden={item.type !== "input"}>
                                                <p>{item.title}</p>
                                                <input type="text"  hidden={this.state.isDisabled} placeholder={"请输入"+item.title} value={this.state.data[item.key]} onChange={(ev)=>{this.gotoChangeValue(ev,item)}} />
                                                <div className="ids" hidden={!this.state.isDisabled}>{this.state.data[item.key]?this.state.data[item.key]:'暂无'}</div>
                                            </div>
                                            <div className="item" hidden={item.type !== "date"}>
                                                <p>{item.title}</p>
                                                <div className="ibox" hidden={this.state.isDisabled}>{this.state.data[item.key]?this.state.data[item.key]:'选择'+item.title}
                                                    <DatePicker className="i_date" onChange={(data,date)=>{this.onChangeDate(data,date,item)}} />
                                                    <img hidden={this.state.data[item.key]} alt="" className="icon" src="assets/imgs/xia2.png" />
                                                    <img hidden={!this.state.data[item.key]} onClick={(ev)=>{this.gotoRemove(ev,item)}} alt="" className="icon2" src="assets/imgs/close.png" />
                                                </div>
                                                <div className="ids" hidden={!this.state.isDisabled}>{this.state.data[item.key]?this.state.data[item.key]:'暂无'}</div>
                                            </div>
                                            <div className="item" hidden={item.type !== "multistage"}>
                                                <p>{item.title}</p>
                                                <div className="ids" hidden={!this.state.isDisabled}>{this.state.data[item.key]?this.state.data[item.key]:'暂无'}</div>
                                                <div className="ibox" hidden={this.state.isDisabled}>{this.state.data[item.key]?this.state.data[item.key]:'选择'+item.title}
                                                <img hidden={this.state.data[item.key]} alt="" className="icon" src="assets/imgs/xia2.png" />
                                                <img hidden={!this.state.data[item.key]} onClick={(ev)=>{this.gotoRemove(ev,item)}} alt="" className="icon2" src="assets/imgs/close.png" />
                                                <Cascader className="i_date"   style={{borderColor:'#fff',flex:'1'}} placeholder=' ' size="large" options={this.state.cityList} onChange={(value,selectedOptions)=>{this.onChange(value,selectedOptions,item)}} />
                                                </div>
                                            </div>

                                            <div hidden={item.type !== "select"}>
                                                <div className="item" hidden={item.key === 'gender'}>
                                                    <p>{item.title}</p>
                                                    <div className="ids" hidden={!this.state.isDisabled}>{this.state.data[item.key]?this.state.data[item.key]:'暂无'}</div>
                                                    <div className="selbox" hidden={this.state.isDisabled} onClick={()=>{this.gotoShow(index)}}>
                                                        {this.state.data[item.key]?(
                                                            this.do(item,this.state.data[item.key])
                                                        ):'选择'+item.title}
                                                        <img hidden={this.state.data[item.key]} alt="" className="icon" src="assets/imgs/xia2.png" />
                                                        <img hidden={!this.state.data[item.key]} onClick={(ev)=>{this.gotoRemove(ev,item)}} alt="" className="icon2" src="assets/imgs/close.png" />
                                                        <div className="sels" hidden={!item.show} onMouseLeave={()=>{this.gotoLeave(index)}}>
                                                            {
                                                                this.state.dicData[item.key]?this.state.dicData[item.key].map((elem,num)=>{
                                                                    return <h4 key={num} className={this.state.data[item.key] === elem.name?'hover':''} onClick={()=>{this.gotoChoose(elem,item,index)}}>{elem.name}</h4>
                                                                }):null
                                                            }
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                    </div>
                            })
                        }
                        </div>

                        <div className="aBtns" hidden={this.state.isDisabled}>
                            <button className="btn1" onClick={()=>{this.props.closeEditModal()}}>取消</button>
                            <button className="btn2" onClick={()=>{this.gotoAdd()}}>确认</button>
                        </div>
                        <div className="aBtns" hidden={!this.state.isDisabled}>
                            <button className="btn1" onClick={()=>{this.setState({isDisabled:false})}}>编辑</button>
                            <button className="btn2" onClick={()=>{this.props.closeEditModal()}}>关闭</button>
                        </div>
                    </div>
            </div>
        )
    }
}
export default withRouter(editModal);